package com.mf.morefun.ui.myclass;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.ClipboardManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.ClassCodeBean;
import com.mf.morefun.bean.ClassListBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.MyRequestListener;
import com.mf.morefun.requestbean.RequestClassCodeBean;
import com.mf.morefun.ui.myclass.fragment.ArrangeHomeWorkFragment;
import com.mf.morefun.ui.myclass.fragment.ClassNumberFragment;
import com.mf.morefun.ui.myclass.fragment.HomeWorkFragment;
import com.mf.morefun.ui.myclass.fragment.RankFragment;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.TransformationUtils;
import com.mf.morefun.widget.NetErrorPop;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClassDetailActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_class)
    TextView tvClass;
    @BindView(R.id.tv_invitation)
    TextView tvInvitation;
    @BindView(R.id.iv_rank)
    ImageView ivRank;
    @BindView(R.id.tv_rank)
    TextView tvRank;
    @BindView(R.id.ll_rank)
    LinearLayout llRank;
    @BindView(R.id.iv_homework)
    ImageView ivHomework;
    @BindView(R.id.tv_homework)
    TextView tvHomework;
    @BindView(R.id.ll_homework)
    LinearLayout llHomework;
    @BindView(R.id.iv_classnum)
    ImageView ivClassnum;
    @BindView(R.id.tv_classnum)
    TextView tvClassnum;
    @BindView(R.id.ll_classnum)
    LinearLayout llClassnum;
    @BindView(R.id.iv_arrange)
    ImageView ivArrange;
    @BindView(R.id.tv_arrange)
    TextView tvArrange;
    @BindView(R.id.ll_arrange)
    LinearLayout llArrange;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    private ClassListBean mClassListBean;
    private FragmentManager fManager;
    private RankFragment mRankFragment;//排行榜
    private HomeWorkFragment mHomeWorkFragment;//作业
    private ClassNumberFragment mClassNumberFragment;//班级成员
    private ArrangeHomeWorkFragment mArrangeHomeWorkFragment;//布置作业
    private SPUtils mSPutils;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_classdetail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSPutils = new SPUtils(getApplicationContext());
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSPutils.getString(Configuration.USERPHONE), mSPutils.getString(Configuration.USERPASSWORD));
        }
        mClassListBean = (ClassListBean) getIntent().getSerializableExtra("CLASSBENA");
        if (null != mClassListBean) {
            CircleCrop circleCrop = new CircleCrop();
            RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
            Glide.with(ClassDetailActivity.this).asBitmap().load(mClassListBean.getClassBelong().getCover()).listener(new MyRequestListener(ivHead, ClassDetailActivity.this, DeviceUtils.dip2px(ClassDetailActivity.this, 60), DeviceUtils.dip2px(ClassDetailActivity.this, 60))).apply(options).into(new TransformationUtils(ivHead, ClassDetailActivity.this, DeviceUtils.dip2px(ClassDetailActivity.this, 60), DeviceUtils.dip2px(ClassDetailActivity.this, 60)));
        }
        fManager = getSupportFragmentManager();
        selectItem(0);
        changeButtonColor(0);
        if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getUserType())) {
            tvInvitation.setVisibility(View.GONE);
            llClassnum.setVisibility(View.GONE);
            llArrange.setVisibility(View.GONE);
            tvClass.setVisibility(View.VISIBLE);
        } else {
            if (MoreFunApplication.loginBean.getResult().getUserType().equals("1")) {//1学员
                tvInvitation.setVisibility(View.GONE);
                llClassnum.setVisibility(View.GONE);
                llArrange.setVisibility(View.GONE);
                tvClass.setVisibility(View.VISIBLE);
            } else if (MoreFunApplication.loginBean.getResult().getUserType().equals("2")) {//2老师
                tvInvitation.setVisibility(View.VISIBLE);
                llClassnum.setVisibility(View.VISIBLE);
                llArrange.setVisibility(View.VISIBLE);
                tvClass.setVisibility(View.GONE);
            } else if (MoreFunApplication.loginBean.getResult().getUserType().equals("3")) {//3管理员
                tvInvitation.setVisibility(View.VISIBLE);
                llClassnum.setVisibility(View.VISIBLE);
                llArrange.setVisibility(View.VISIBLE);
                tvClass.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (null != mHomeWorkFragment) {
                mHomeWorkFragment.initHomeWorkList(true);
            }
        }
    }

    private void changeButtonColor(int index) {
        switch (index) {
            case 0:
                ivRank.setImageResource(R.mipmap.myclass_rankinglist);
                tvRank.setTextColor(getResources().getColor(R.color.white));
                llRank.setBackgroundResource(R.mipmap.mineselected);
                ivHomework.setImageResource(R.mipmap.myclass_homework_nomol);
                tvHomework.setTextColor(0xff666666);
                llHomework.setBackgroundResource(R.mipmap.noselect);
                ivClassnum.setImageResource(R.mipmap.myclass_classnumber_nmorl);
                tvClassnum.setTextColor(0xff666666);
                llClassnum.setBackgroundResource(R.mipmap.noselect);
                ivArrange.setImageResource(R.mipmap.arrange);
                tvArrange.setTextColor(0xff666666);
                llArrange.setBackgroundResource(R.mipmap.noselect);
                break;
            case 1:
                ivRank.setImageResource(R.mipmap.myclass_rankinglist_nmorl);
                tvRank.setTextColor(0xff666666);
                llRank.setBackgroundResource(R.mipmap.noselect);
                ivHomework.setImageResource(R.mipmap.myclass_homework);
                tvHomework.setTextColor(getResources().getColor(R.color.white));
                llHomework.setBackgroundResource(R.mipmap.mineselected);
                ivClassnum.setImageResource(R.mipmap.myclass_classnumber_nmorl);
                tvClassnum.setTextColor(0xff666666);
                llClassnum.setBackgroundResource(R.mipmap.noselect);
                ivArrange.setImageResource(R.mipmap.arrange);
                tvArrange.setTextColor(0xff666666);
                llArrange.setBackgroundResource(R.mipmap.noselect);
                break;
            case 2:
                ivRank.setImageResource(R.mipmap.myclass_rankinglist_nmorl);
                tvRank.setTextColor(0xff666666);
                llRank.setBackgroundResource(R.mipmap.noselect);
                ivHomework.setImageResource(R.mipmap.myclass_homework_nomol);
                tvHomework.setTextColor(0xff666666);
                llHomework.setBackgroundResource(R.mipmap.noselect);
                ivClassnum.setImageResource(R.mipmap.myclass_classnumber);
                tvClassnum.setTextColor(getResources().getColor(R.color.white));
                llClassnum.setBackgroundResource(R.mipmap.mineselected);
                ivArrange.setImageResource(R.mipmap.arrange);
                tvArrange.setTextColor(0xff666666);
                llArrange.setBackgroundResource(R.mipmap.noselect);
                break;
            case 3:
                ivRank.setImageResource(R.mipmap.myclass_rankinglist_nmorl);
                tvRank.setTextColor(0xff666666);
                llRank.setBackgroundResource(R.mipmap.noselect);
                ivHomework.setImageResource(R.mipmap.myclass_homework_nomol);
                tvHomework.setTextColor(0xff666666);
                llHomework.setBackgroundResource(R.mipmap.noselect);
                ivClassnum.setImageResource(R.mipmap.myclass_classnumber_nmorl);
                tvClassnum.setTextColor(0xff666666);
                llClassnum.setBackgroundResource(R.mipmap.noselect);
                ivArrange.setImageResource(R.mipmap.arranged);
                tvArrange.setTextColor(getResources().getColor(R.color.white));
                llArrange.setBackgroundResource(R.mipmap.mineselected);
                break;
        }
    }

    //切换fragment的方法
    private int mIndex = -1;

    private void selectItem(int index) {
        FragmentTransaction transaction = fManager.beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (mIndex == 0) {
                    return;
                }
                mIndex = 0;
                if (mRankFragment == null) {
                    mRankFragment = RankFragment.newInstance(mClassListBean);
                    transaction.add(R.id.fl_content, mRankFragment);
                } else {
                    transaction.show(mRankFragment);
                }
                break;
            case 1:
                if (mIndex == 1) {
                    return;
                }
                mIndex = 1;
                if (mHomeWorkFragment == null) {
                    mHomeWorkFragment = HomeWorkFragment.newInstance(mSPutils.getString(Configuration.USERID), "0", mClassListBean.getClassBelong().getId(), MoreFunApplication.loginBean.getResult().getUserType());
                    transaction.add(R.id.fl_content, mHomeWorkFragment);
                } else {
                    transaction.show(mHomeWorkFragment);
                }
                break;
            case 2:
                if (mIndex == 2) {
                    return;
                }
                mIndex = 2;
                if (mClassNumberFragment == null) {
                    mClassNumberFragment = ClassNumberFragment.newInstance(mClassListBean);
                    transaction.add(R.id.fl_content, mClassNumberFragment);
                } else {
                    transaction.show(mClassNumberFragment);
                }
                break;
            case 3:
                if (mIndex == 3) {
                    return;
                }
                mIndex = 3;
                if (mArrangeHomeWorkFragment == null) {
                    mArrangeHomeWorkFragment = ArrangeHomeWorkFragment.newInstance(mClassListBean);
                    transaction.add(R.id.fl_content, mArrangeHomeWorkFragment);
                } else {
                    transaction.show(mArrangeHomeWorkFragment);
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (mRankFragment != null) {
            transaction.hide(mRankFragment);
        }
        if (mHomeWorkFragment != null) {
            transaction.hide(mHomeWorkFragment);
        }
        if (mClassNumberFragment != null) {
            transaction.hide(mClassNumberFragment);
        }
        if (mArrangeHomeWorkFragment != null) {
            transaction.hide(mArrangeHomeWorkFragment);
        }
    }


    @Override
    protected void initData() {

    }

    @OnClick({R.id.iv_back, R.id.tv_invitation, R.id.ll_rank, R.id.ll_homework, R.id.ll_classnum, R.id.ll_arrange})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_invitation://邀请学员
                //邀请码
                if (null != mClassListBean && null != MoreFunApplication.loginBean && null != MoreFunApplication.loginBean.getResult() && null != MoreFunApplication.loginBean.getResult().getOrgan()) {
                    initGetClassCode(MoreFunApplication.loginBean.getResult().getOrgan().getId(), mClassListBean.getClassBelong().getId());
                }
                break;
            case R.id.ll_rank://排行榜
                selectItem(0);
                changeButtonColor(0);
                break;
            case R.id.ll_homework://作业
                selectItem(1);
                changeButtonColor(1);
                break;
            case R.id.ll_classnum://班级成员
                selectItem(2);
                changeButtonColor(2);
                break;
            case R.id.ll_arrange://布置作业
                selectItem(3);
                changeButtonColor(3);
                break;
        }
    }

    private void initGetClassCode(String orginId, String classId) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.GETCLASSCODE);
        RequestClassCodeBean requestClassCodeBean = new RequestClassCodeBean();
        requestClassCodeBean.setId("");
        RequestClassCodeBean.OrganBean organBean = new RequestClassCodeBean.OrganBean();
        organBean.setId(orginId);
        RequestClassCodeBean.InviterClassBean classBean = new RequestClassCodeBean.InviterClassBean();
        classBean.setId(classId);
        requestClassCodeBean.setInviterClass(classBean);
        requestClassCodeBean.setOrgan(organBean);
        params.setBodyContent(JSON.toJSONString(requestClassCodeBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        ClassCodeBean classCodeBean = JSON.parseObject(resultBean.getResult(), ClassCodeBean.class);
                        try {
                            showChangeName(classCodeBean.getInvitationCode());
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(ClassDetailActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    private PopupWindow mNamePop = null;

    //改名字
    private void showChangeName(String classCode) {
        closePop();
        if (null == mNamePop) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_popclasscode, null);
            // 这里启动头像
            RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            EditText edit_name = view.findViewById(R.id.edit_name);
            edit_name.setText(classCode);
            TextView tv_sure = view.findViewById(R.id.tv_sure);
            tv_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    clip.setText(classCode);
                    closePop();
                    ToastUtils.show(getApplicationContext(), "复制成功", 100);
                }
            });
            mNamePop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            mNamePop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mNamePop.setBackgroundDrawable(new BitmapDrawable());
            mNamePop.setFocusable(true);
            mNamePop.update();
            mNamePop.showAtLocation(view, Gravity.CENTER, 0, 0);
            mNamePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mNamePop.dismiss();
                    mNamePop = null;
                }
            });
        }
    }

    private void closePop() {
        if (null != mNamePop) {
            mNamePop.dismiss();
            mNamePop = null;
        }
    }
}
